<?php

namespace app\api\model;

use think\Model;
use think\Db;
use app\mpbase\library\WechatCard as Card;


class WechatCard extends ApiModel
{
	private static $fields = [
		'public' => ['id','logo_url','title','reduce_cost','sub_title','quantity','begin_timestamp','end_timestamp','cat_name','init_quantity','card_id'],
		'details' => ['card_id','store_id','s_images','s_score','s_name','notice','description'],
		'distance' => ['pos_latitude','pos_longitude','pos_latitude','pos_longitude']

	];

	// 追加属性
	protected $append = [
		'expire'
	];
    // 显示的字段名
//    protected $visible = ['card_id','logo_url','brand_name','title','sub_title',
//        'notice','description','date_type','begin_timestamp','end_timestamp',
//        'fixed_term','fixed_begin_term','quantity','createtime','status',
//        'discount','least_cost','reduce_cost','gift','deal_detail','default_detail'];

    protected function base($query)
    {
        $mpId = get_api_applet_id();
        $globalKey = [
            'mp_id'=>$mpId,
            'visible'=>1,
        ];
        $query->where($globalKey);
		//未审核通过的
//		$query->where('status','in',['CARD_STATUS_VERIFY_OK','CARD_STATUS_DISPATCH']);
        $query->where(['pass_check' => 1]);
    }

	//获取有效期
	public function getExpireAttr($value,$data)
	{
		return '有效期'.date("Y-m-d",$data['begin_timestamp']).'至'.date("Y-m-d",$data['end_timestamp']);
	}


	//店铺连接
	public function store()
	{
		return $this->belongsTo('Store','store_id','id')->bind('s_score,s_name,pos_latitude,pos_longitude,s_image,s_images');
	}

	public function category()
	{
		return $this->belongsTo('StoreCat','cat_id','id')->bind('cat_name');
	}

    //按照分类来获取卡券分页
    public static function getList($map=[],$page = 1, $row = 10)
    {
        $res['data'] = self::baseList($map,$page, $row,array_merge(self::$fields['public'],self::$fields['distance']));
        $res['total'] = $total = self::where($map)
            ->where('card_id','<>',0)
            ->where('quantity','<>',0)
            ->where('status','neq','CARD_STATUS_DELETE')
            ->where('end_timestamp','>',time())
            ->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
        return $res;
    }

    //根据商品Id 获取评论
    public static function getListByUser($userId ,$page = 1, $row = 10)
    {
        $map = ['user_id'=>$userId];
        $res['data'] = WechatCardCode::where($map)
            ->with('info')
            ->page($page, $row)
            ->order('state desc,begin_time asc')
            ->select();
        $res['total'] = $total = WechatCardCode::where($map)->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
        return $res;
    }

	//获取主题下的优惠券
	public function groupList($map)
	{
		$data = $this::with('category')
            ->where('id','in',$map)
            ->select()
            ->visible(self::$fields['public']);
		$res = empty($data)? [] :$data->toArray();
		return $res;
	}

	//基本查询(单张优惠券查询)
	public static function baseList($map=[],$page = 1, $row = 10,$field = [])
	{
		$res['data'] = self::with('category,store')
	                ->where($map)
			->page($page,$row)
			->order('createtime desc')
            ->where('card_id','<>',0)
            ->where('quantity','<>',0)
            ->where('status','neq','CARD_STATUS_DELETE')
            ->where('end_timestamp','>',time())
			->select()
		    ->visible($field);
        return $res;
//		$res['data'] = Db::table('uct_wechat_card')->alias('card')
//			->join('uct_hk_store store','store.id = card.store_id and  store.area_id=3')
//			->join('uct_store_cat cat','card.cat_id = cat.id')
//			->where($map)
//			->order('card.createtime desc')
//			->field($field)
//			->select();
//		return $res;
	}


	//获取指定的id 详情
	public static function getById($map = [])
	{
	    $data = self::baseList($map,1,1,array_merge(self::$fields['public'],self::$fields['details']));
        $arr = $data['data']->toArray();
        $arr = $arr[0];

        $arr['s_image'] = $arr['s_images'][0];
		$arr['explain'] = [
		    'sub_title'  => $arr['sub_title'],
			'time'       => '有效期'.date("Y-m-d",$arr['begin_timestamp']).'至'.date("Y-m-d",$arr['end_timestamp']),
			'notice'     => $arr['notice'],
//			'description' => explode(PHP_EOL,$arr['description'])
            'description' => $arr['description']
        ];
		//减掉description尾部的字符
//        foreach($arr['explain']['description'] as $key => &$val){
//            rtrim($val);
//        }
		//删掉数据
		unset($arr['sub_title']);
		unset($arr['begin_timestamp']);
		unset($arr['end_timestamp']);
		unset($arr['notice']);
		unset($arr['description']);
		$res['data'] = $arr;
		return $res;
	}

	//获取
    public function couponPage($map,$order,$arr,$page=1,$row=10)
    {
		$field = ['card.id','card.logo_url','card.title','card.reduce_cost','card.sub_title','card.quantity','card.init_quantity','card.begin_timestamp','card.end_timestamp','cat.cat_name',
		'card.card_id','card.store_id','store.s_image','store.s_score','store.s_name','pos_longitude','pos_latitude'];
        $field[] = 'get_distance('.$arr['lng'].',"'.$arr['lat'].'",store.pos_longitude,store.pos_latitude) as distance';

        //审核通过的卡券
        $map['pass_check'] = 1;

        $model =  Db::table('uct_wechat_card')->alias('card')
            ->join('uct_hk_store store','store.id = card.store_id')
            ->join('uct_store_cat cat','card.cat_id = cat.id')
            ->where($map)
            ->where('card.quantity','<>',0)
            ->where('card.status','neq','CARD_STATUS_DELETE')
            ->where('card.end_timestamp','>',time());

		$res['data'] = $model->order($order)
			->field($field)
			->page($page,$row)
			->select();

        foreach($res['data'] as $key => &$val)
        {
            $val['expire'] = '有效期'.date("Y-m-d",$val['begin_timestamp']).'至'.date("Y-m-d",$val['end_timestamp']);
        }

        $res['total'] = $total = Db::table('uct_wechat_card')->alias('card')
            ->join('uct_hk_store store','store.id = card.store_id')
            ->join('uct_store_cat cat','card.cat_id = cat.id')
            ->where($map)
            ->where('card.quantity','<>',0)
            ->where('card.status','neq','CARD_STATUS_DELETE')
            ->where('card.end_timestamp','>',time())
            ->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
		return $res;
    }

    //获取指定用户领取到的卡券
    public static function  getUserCard($openid)
    {
//        $mp_openid = Db('User')->where(['openid' => $openid])->find();
        $page = input('page',1);
        $row = input('row',5);
        $data = (new Card())->getUserCard($openid)->card_list;
        $arr = [];
        foreach($data as $key => $val){
            $arr[] = $val['card_id'];
        }
        $in = implode(",",$arr);
        $result = self::with('category')
            ->where('card_id','in',$in)
            ->select()
            ->visible(self::$fields['public']);
        $res['data'] = empty($data)? [] :$result->toArray();

        $res['total'] = $total = self::where('card_id','in',$in)->count();

        $res['has_more'] = ceil($total / $row) > $page ? true : false;

        foreach($res['data'] as $key => &$val){
            foreach($data as $k => $v){
                if($val['card_id'] == $v['card_id']){
                    $val['code'] = $v['code'];
                }
            }
        }
        return $res;
    }

    //获取用户核销掉的卡券
    public static function getConsumeCard($mp_openid)
    {
       $page = input('page',1);
       $row = input('row',5);
       $field = ['card.id','card.store_id','card.logo_url','card.title','card.reduce_cost','card.sub_title','card.quantity','card.begin_timestamp','card.end_timestamp','card.init_quantity','card.card_id','consume.id as consume_id','consume.createtime','consume.is_comment'];
       $res['data'] = Db::table('uct_consume_card')->alias('consume')
           ->join('uct_wechat_card card','consume.card_id = card.card_id')
           ->where(['consume.user_openid' => $mp_openid])
           ->order('createtime desc')
           ->field($field)
           ->page($page,$row)
           ->select();

       $res['total'] = $total = Db::table('uct_consume_card')->alias('consume')
           ->join('uct_wechat_card card','consume.card_id = card.card_id')
           ->where(['consume.user_openid' => $mp_openid])
           ->count();

        $res['has_more'] = ceil($total / $row) > $page ? true : false;

       foreach($res['data'] as $key => &$val)
       {
           $val['expire'] = '有效期'.date("Y-m-d",$val['begin_timestamp']).'至'.date("Y-m-d",$val['end_timestamp']);
       }
        return $res;
    }

}
